//
//  PersonalCenter.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/7/19.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON
class PersonalCenter: HMTableViewController {
    
    // 数据
    var dataAry: Array<Any>!
    var maskView: UIView?
    private var hmUser =  HMLoginParam.share.user // 获取登陆的本地信息
    private var selectIndexPath: IndexPath?
    override func load() {
        self.title = "个人信息"
        self.tableView.register(PersonalCell.classForCoder(), forCellReuseIdentifier: "PersonalCell")
        self.tableView.register(OptionCell.classForCoder(), forCellReuseIdentifier: "OptionCell")
        //禁止滑动
        self.tableView.isScrollEnabled = false
        
        
        self.dataAry = [["icon":"LifePattern", "title": "历史消息记录"],["icon":"LifePattern", "title": "生活模式", "describe": "在校"],["icon":"motion", "title": "运动模式", "describe": "从不"],["icon":"disease", "title": "我的疾病"],["icon":"certification", "title": "医生认证"],["icon":"share", "title": "分享二维码"],["icon":"wallet", "title": "我的钱包"],["icon":"Setup", "title": "设置与声明"]]
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let indexPath: IndexPath = IndexPath.init(row: 0, section: 0)
        let newcell = self.tableView.cellForRow(at: indexPath) as! PersonalCell
        newcell.updatePersonalData()
//        self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
//        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
        super.hideHeader()
        super.hideFooter()
        

        
    }
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }else {
            return self.dataAry.count
        }
    }
    // cell 数据
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if(indexPath.section == 0) {
//            let newcell = cell as! PersonalCell
        }else {
            let newcell = cell as! OptionCell
            let newDic = self.dataAry[indexPath.row] as! NSDictionary
            let jsonData = newDic.mj_JSONData()
            let js = try? JSON.init(data: jsonData!)
              newcell.setJson(json:js!)
        }
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section  == 0 {
            return 100
        }else {
            return 50
        }
    }
    override func cellForRow(atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if(indexPath.section == 0) {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "PersonalCell") as! PersonalCell
            return cell
        }else {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "OptionCell") as! OptionCell
            return cell
        }
        
    }
   override  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let newDic = self.dataAry[indexPath.row] as! NSDictionary
    let _title = newDic["title"] as! String
    self.selectIndexPath = indexPath
    
    if indexPath.section == 0 {
        let user = HMUserInformation()
        self.pushViewController(user)
    }else {
        if(indexPath.row == 7) {
            let configure = ConfigureFocus()
            configure.title = _title
            self.pushViewController(configure)
        }else if (indexPath.row == 1 || indexPath.row == 2) {
            var ary1 = Array<String>()
            if indexPath.row == 1 {
                HMPickerView.sharePicker.sign = "liveMode"
                if !(HMLoginParam.share.liveMode?.isEmpty)! {
                    for v  in HMLoginParam.share.liveMode! {
                        var dic = v as! Dictionary<String, Any>
                        let str = dic["desc"] as! String
                        ary1.append(str)
                    }
                }
            }else {
                HMPickerView.sharePicker.sign = "sportMode"
                if !(HMLoginParam.share.sportMode?.isEmpty)! {
                 for v  in HMLoginParam.share.sportMode! {
                    var dic = v as! Dictionary<String, Any>
                    let str = dic["desc"] as! String
                    ary1.append(str)
                 }
                }
            }
        
            HMPickerView.sharePicker.delegate = self
            HMPickerView.creator(nil, picker: ["Ary" : ary1])
        }else if (indexPath.row == 3) {
            
            let disease = HMMyDisease()
            
            NetRequestTool.shareInstance.met = .get
            NetRequestTool.request(url: "user/illness-item-config", parameters: [:], success: { (json) in

                if !json["data"].isEmpty {
                     disease.diseaseList = json["data"]
                }
            }, fail: { (code, msg) in
                
            }) {
                NetRequestTool.shareInstance.met = .get
                NetRequestTool.request(url: "user/illness", parameters: [:], success: { (userJson) in
                    disease.myDiseaseList = userJson["data"]
                    self.pushViewController(disease)
                }, fail: { (error, msg) in
//                     print("personalCenter,-->>", msg)
                }, complete: {})
            }
        }else if (indexPath.row == 4) {
          let authentication = Authentication()
          self.pushViewController(authentication)
            
        }else if (indexPath.row == 6) {
            let wallet = HMMyWallet()
            wallet.title = _title
            self.pushViewController(wallet)
        }
    }
    


    }
    
    @objc func onMask(sender: UITapGestureRecognizer) {
         HMPickerView.hidePickeView()
         maskView?.removeFromSuperview()
    }
    
    
    
    override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
        print("-----")
    }
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
    
    
}

extension PersonalCenter: HMPickerViewDelegate {
    func cancel() {
         maskView?.removeFromSuperview()
    }
    func selectValue(value: String, row: Int, component: Int) {
        HMUtils.share.showHUD("正在保存中...")
        var param : [String : Any] = ["sex": self.hmUser["sex"]!, "height":self.hmUser["height"]!,"weight":self.hmUser["weight"]!, "liveMode": 1, "sportMode": 1]
        
        if HMPickerView.sharePicker.sign == "sportMode" {
            
            var dic = HMLoginParam.share.sportMode![row] as! Dictionary<String, Any>
            let i = dic["id"] as! Int
            
            param["sportMode"] = i
        }else if  HMPickerView.sharePicker.sign == "liveMode" {
            
                var dic = HMLoginParam.share.liveMode![row] as! Dictionary<String, Any>
                let i = dic["id"] as! Int
            
            param["liveMode"] = i
        }
        
      
        NetRequestTool.requestForJSON(url: "user/base-info", parameters: param, success: { (json) in
            HMUtils.share.hideHUD()
            HMLoginParam.updateUser(self.hmUser)
        }, fail: { (error, msg) in
            HMUtils.share.hideHUD()
        }) {}
    }
    
}
